package com.efounder.chat.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.efounder.chat.R;
import com.efounder.chat.http.JFCommonRequestManager;
import com.efounder.chat.utils.AESSecretUtil;
import com.efounder.chat.utils.CommonThreadPoolUtils;
import com.efounder.chat.utils.FileSizeUtil;
import com.efounder.chat.utils.FileTypeIconUtil;
import com.efounder.chat.utils.FileUtil;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.pansoft.chat.input.SecretInputView;
import com.efounder.pansoft.chat.record.voice.FileDeleteUtil;
import com.efounder.tbs.FileDisplayActivity;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.tencent.smtt.sdk.TbsVideo;
import com.utilcode.util.FileIOUtils;
import com.utilcode.util.ToastUtils;

import org.apache.tools.ant.util.FileUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

/**
 * 密件的下载与查看
 */
public class SecretFileDisplayActivity extends BaseActivity implements View.OnClickListener {

    private ImageView mIvFileType;
    private TextView mTvFileName;
    private TextView mTvFileSize;
    private Button mBtFileButton;
    private TextView mTvDownload;
    private ProgressBar mPbProgress;
    private boolean isDown;
    private String url;//加密图片路径
    private String localPath;//消息里的加密图片本地路径
    private boolean isFromLocal;//是否本地消息
    private String password;//解密密码
    private String fileName;
    private String fileType;
    private String fileSize;
    private static final String TAG = "SecretFileDisplayActivity";

    //消息url中截取的文件名称
    private String urlFileName;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_secret_file_display);
        initView();
        initData();
    }

    private void initData() {


        if (getIntent().getExtras() != null) {
            //得到消息中的密件地址
            mTvDownload.setText(String.format("下载中...(%1$s/%2$s)", "0KB", "0KB"));
            Intent intent = getIntent();
            try {
                isFromLocal = intent.getBooleanExtra("fromLocal", false);
                JSONObject jsonObject = new JSONObject(getIntent().getStringExtra("message"));
                url = jsonObject.optString("url");
                localPath = jsonObject.optString("FileLocalPath", "");
                fileName = jsonObject.optString("FileName", "");
                fileType = jsonObject.optString("FileType", "");
                fileSize = jsonObject.optString("FileSize", "");


            } catch (JSONException e) {
                e.printStackTrace();
            }
            if (url == null) {
                ToastUtils.showShort(R.string.wrchatview_dcryption_failed);
                return;
            }

            //有password则用password解密
            if (getIntent().getExtras().containsKey("password")) {
                password = getIntent().getStringExtra("password");
//                passwordDecrypt();
            }


            mTvFileName.setText(fileName);
            FileTypeIconUtil.setFileIconByFileType(mIvFileType, fileType);
            mTvFileSize.setText(fileSize);

            try {
                //通过url截取文件名
                String fileName = url.substring(0, url.lastIndexOf("/"));
                urlFileName = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
            } catch (Exception e) {
                e.printStackTrace();
                urlFileName = System.currentTimeMillis() + "";
            }

            if (isFromLocal) {
                if (isLocalFileExist()) {
                    mBtFileButton.setText(R.string.wrchatview_view_serect);
                } else {
                    if (judgeFileHasDown()) {
                        mBtFileButton.setText(R.string.wrchatview_view_serect);
                    } else {
                        mBtFileButton.setText(R.string.wrchatview_down_serect);
                    }

                }
            } else {

                if (judgeFileHasDown()) {
                    mBtFileButton.setText(R.string.wrchatview_view_serect);
                } else {
                    mBtFileButton.setText(R.string.wrchatview_down_serect);
                }
            }
        }
    }

    //判断文件是否已经下载
    private boolean judgeFileHasDown() {
        File file = new File(FileUtil.encryptFilePath + urlFileName);
        if (file != null && file.exists()) {
            return true;
        }
        return false;
    }

    private void initView() {

        TextView tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText(R.string.wrchatview_secret_file);
        mIvFileType = (ImageView) findViewById(R.id.iv_display_file_type);
        mTvFileName = (TextView) findViewById(R.id.tv_secret_file_name);
        mTvFileSize = (TextView) findViewById(R.id.tv_secret_file_size);
        mBtFileButton = (Button) findViewById(R.id.bt_secret_file_display_button);
        mTvDownload = (TextView) findViewById(R.id.tv_secret_file_download_size);
        mPbProgress = (ProgressBar) findViewById(R.id.pb_secret_file_progress);
        mBtFileButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        int i = view.getId();
        if (i == R.id.bt_secret_file_display_button) {

            String filePath = FileUtil.encryptFilePath;

            //本地存在加密文件，则直接解密
            if (isLocalFileExist()) {
                decryptBytes(localPath);
                return;
            }
            //检查加密文件是否已经下载
            File file = new File(filePath + urlFileName);
            if (file != null && file.exists()) {
                decryptBytes(file.getAbsolutePath());
                return;
            }

            setButtonGone();
            //下载加密文件，完成后解密
            downloadImageBytes(url, filePath, urlFileName);
        }
    }

    @Override
    public void back(View v) {
        finish();
    }

    /**
     * 设置按钮显示
     */
    private void setButtonVisible() {
        mTvDownload.setVisibility(View.GONE);
        mPbProgress.setVisibility(View.GONE);
        mBtFileButton.setVisibility(View.VISIBLE);
    }

    /**
     * 设置按钮不显示
     */
    private void setButtonGone() {
        mTvDownload.setVisibility(View.VISIBLE);
        mPbProgress.setVisibility(View.VISIBLE);
        mBtFileButton.setVisibility(View.GONE);
    }

    /**
     * 判断是否存在本地文件
     *
     * @return true/false
     */
    private boolean isLocalFileExist() {

        File file = new File(localPath);
        if (file.exists()) {
            return true;
        }

        return false;
    }

    /**
     * 解密bytes并生成本地文件
     */
    private void decryptBytes(final String filePath) {
        SecretInputView.showTcLoading(this, ResStringUtil.getString(R.string.wrchatview_dcryptioning));
        CommonThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    FileDeleteUtil.deleteDirectory(FileUtil.decryptTemp);
                    //创建临时文件夹
                    final File file = new File(FileUtil.decryptTemp);
                    if (!file.exists()) {
                        file.mkdirs();
                    }

                    AESSecretUtil aesSecretUtil = new AESSecretUtil(password);
                    //解密bytes
                    final byte[] targetBytes = aesSecretUtil.decrypt(FileIOUtils.readFile2BytesByStream(filePath));
                    //解密之后的文件路径（解密的文件名使用消息中的文件名）
                    final String decreptFilePath = (FileUtil.decryptTemp + fileName).replace(".bin", "");
                    FileIOUtils.writeFileFromBytesByStream(decreptFilePath, targetBytes);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            setButtonVisible();
                            SecretInputView.dismissTcLoading();
                            //打开文件
                            File file = new File(decreptFilePath);
                            if (!file.exists()) {
                                ToastUtil.showToast(SecretFileDisplayActivity.this, R.string.wrchatview_dcryption_failed);
                                return;
                            }

                            //系统版本>=8.1 默认方式打开
//                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
//                                defaultOpenFile(decreptFilePath);
//                                return;
//                            }
                            //如果tbs内核内有加载成功，使用默认方式
                            if (EnvironmentVariable.getProperty("tbsLoadResult", "false")
                                    .equals("false")) {
                                defaultOpenFile(decreptFilePath);
                                return;
                            }

                            if ("pdf".equals(fileType.toLowerCase())
                                    || "docx".equals(fileType.toLowerCase())
                                    || "doc".equals(fileType.toLowerCase())
                                    || "xls".equals(fileType.toLowerCase())
                                    || "xlsx".equals(fileType.toLowerCase())
                                    || "ppt".equals(fileType.toLowerCase())
                                    || "pptx".equals(fileType.toLowerCase())) {
                                //调用腾讯浏览服务
                                FileDisplayActivity.show(SecretFileDisplayActivity.this, decreptFilePath);

                            } else if ("mp4".equals(fileType.toLowerCase())
                                    || "avi".equals(fileType.toLowerCase())
                                    || "rmvb".equals(fileType.toLowerCase())
                                    || "3gp".equals(fileType.toLowerCase())
                                    || "mpg".equals(fileType.toLowerCase())
                                    || "mpeg".equals(fileType.toLowerCase())) {
                                //调用腾讯视频浏览服务
                                if (TbsVideo.canUseTbsPlayer(SecretFileDisplayActivity.this)) {
                                    TbsVideo.openVideo(SecretFileDisplayActivity.this, decreptFilePath);

                                } else {
                                    defaultOpenFile(decreptFilePath);
                                }
                            } else {
                                defaultOpenFile(decreptFilePath);
                            }
                        }

                    });

                } catch (Exception e) {
                    SecretInputView.dismissTcLoading();
                    e.printStackTrace();
                    ToastUtils.showShort(R.string.wrchatview_dcryption_failed);
                }
            }
        });

    }

    public void defaultOpenFile(String decreptFilePath) {
        Intent intent = FileUtil.openFile(decreptFilePath);
        if (intent != null) {
            startActivity(intent);
        } else {
            ToastUtil.showToast(SecretFileDisplayActivity.this, R.string.wrchatview_dcryption_failed);
        }
    }

    /**
     * 下载文件为bytes,然后解密
     *
     * @param url
     */
    private void downloadImageBytes(final String url, final String filePath,
                                    final String fileName) {
        JFCommonRequestManager.getInstance()
                .downLoadFile(TAG, url, fileName, filePath, new JFCommonRequestManager.ReqProgressCallBack<File>() {
                    @Override
                    public void onProgress(long total, long current) {
                        try {

                            mPbProgress.setProgress((int) (current * 100 / total));
                            //  mTvDownload.setText((int) (current * 100 / total) + "%");
                            String downSize = FileSizeUtil.FormetFileSize(current);
                            mTvDownload.setText(String.format(ResStringUtil.getString(R.string.wrchatview_downing), downSize, fileSize));

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onReqSuccess(File result) {
                        mBtFileButton.setText(R.string.wrchatview_view_serect);
                        setButtonVisible();
                        decryptBytes(result.getAbsolutePath());
                    }

                    @Override
                    public void onReqFailed(String errorMsg) {
                        setButtonVisible();
                        FileUtils.delete(new File(filePath, fileName));
                        ToastUtils.showShort(R.string.wrchatview_down_fail);

                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        FileDeleteUtil.deleteDirectory(FileUtil.decryptTemp);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}
